import functools

from flask import session, abort, current_app, g

from info.utils.models import User


# 自定义过滤器, 实现索引格式转换
def func_index_convert(value):
    index_dict = {1: 'first', 2: 'second', 3: 'third'}

    return index_dict.get(value, '')


# 获取用户的登录信息
def user_login_data(f):  # f = demo1
    @functools.wraps(f)
    def wrappers(*args, **kwargs):
        # 获取session中的user_id
        user_id = session.get("user_id")

        # 根据 `user_id` 可以取出 `用户的数据`
        user = None
        if user_id:  # 用户已登录

            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)
                return abort(500)
        g.user = user
        # 获取函数的名称
        print(wrappers.__name__)
        return f(*args, **kwargs)

    return wrappers
